import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class PesoControl{
    Banco banco = new Banco();

    void calculaSaida(String caminhao, int pesoAtual, int kmAtual) {
        try {
            PreparedStatement st = banco.con.prepareStatement("INSERT INTO cooperativa.entrada2 (caminhao, peso_material, km_rodado, data)"
                                                                + " VALUES(?, ?, ?, ?)");
            st.setString(1, caminhao);
            st.setInt(2, pesoAtual);
            st.setInt(3, kmAtual);
            st.setTimestamp(4, Timestamp.valueOf("0001-01-01 00:00:00"));
            st.executeUpdate();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex, "Erro",1);
        }
    }
    
    void calculaEntrada(String caminhao, int pesoAtual, int kmAtual) {
        try {
            PreparedStatement st = banco.con.prepareStatement("SELECT peso_material, km_rodado FROM cooperativa.entrada2 WHERE data=? AND caminhao=?");
            st.setTimestamp(1, Timestamp.valueOf("0001-01-01 00:00:00"));
            st.setString(2, caminhao);
            ResultSet rs = st.executeQuery();
            if(rs.next()){
                EntradaMaterial ent = new EntradaMaterial(caminhao, rs.getInt(1), rs.getInt(2));
                ent.calcula(pesoAtual, kmAtual);
                st = banco.con.prepareStatement("UPDATE cooperativa.entrada2 SET peso_material=?, km_rodado=?, data=? WHERE data=? AND caminhao=?");
                st.setInt(1, ent.getPeso());
                st.setInt(2, ent.getKm());
                Date d = new Date();
                st.setTimestamp(3, new Timestamp(d.getTime()));
                st.setTimestamp(4, Timestamp.valueOf("0001-01-01 00:00:00"));
                st.setString(5, caminhao);
                st.executeUpdate();
            } else {
                JOptionPane.showMessageDialog(null, "Placa Incorreta!", "Erro",1);
            }
            
            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex, "Erro",1);
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    void limparEntradas(){
        
        try {
            PreparedStatement st = banco.con.prepareStatement("DELETE FROM cooperativa.entrada2 WHERE data=?");
            st.setTimestamp(1, Timestamp.valueOf("0001-01-01 00:00:00"));
            st.executeUpdate();
            
        } catch (SQLException ex) {
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
